<?php

    use think\Db;
    use cmf\lib\Storage;
    // 应用公共文件
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    require_once dirname(__FILE__).'/redis.php';

    /* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
        $checkstr=trim($checkstr);
		$checkstr=urldecode($checkstr);

		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}
		return $str;	
	}
    
    /* 检验手机号 */
	function checkMobile($mobile){
		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		if($ismobile){
			return 1;
		}
        
        return 0;
		
	}
    
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}
    
    /**
     * 转化数据库保存图片的文件路径，为可以访问的url
     * @param string $file  文件路径，数据存储的文件相对路径
     * @param string $style 图片样式,支持各大云存储
     * @return string 图片链接
     */
    function get_upload_path($file, $style = 'watermark')
    {
        if (empty($file)) {
            return '';
        }

        if (strpos($file, "http") === 0) {
            return $file;
        } else if (strpos($file, "/") === 0) {
            return cmf_get_domain() . $file;
        } else {
			
			$configpri=getConfigPri();
			$fileinfo=explode("_",$file);//上传云存储标识：qiniu：七牛云；aws：亚马逊

			$length=strlen($fileinfo[0])+1;
			if($fileinfo[0]=='qiniu'){				 
				// 七牛上传 
				$storage = Storage::instance();
				$file=substr($file,$length);
				return html_entity_decode($storage->getImageUrl($file, $style));
				
            }else if($fileinfo[0]=='aws'){
                 // 亚马逊上传 
				$space_host= $configpri['aws_hosturl'];
				$file=substr($file,$length);
				return html_entity_decode($space_host."/".$file);
            }else{
				$storage = Storage::instance();
				return $storage->getImageUrl($file, $style);
            }
        }
    }
	
	
	/**
	 * 上传文件地址添加区分标识：qiniu：七牛云；aws：亚马逊
	 */
	function set_upload_path($file){
		if (empty($file)) {
            return '';
        }
        if (strpos($file, "http") === 0) {
            return $file;
        } else if (strpos($file, "/") === 0) {
            return cmf_get_domain() . $file;
        } else {
			$configpri=getConfigPri();
			$cloudtype=$configpri['cloudtype'];
			if($cloudtype=='1'){//1：七牛云存储；2：亚马逊存储
				$filepath= "qiniu_".$file;
			}else if($cloudtype=='2'){//亚马逊存储
				$filepath="aws_".$file;
			}else{
				$filepath=$file;
			}
		}
		return $filepath;
	}

    /* 公共配置 */
    function getConfigPub() {
        $key='getConfigPub';
        $config=getcaches($key);
        if(!$config){
            $config= Db::name('option')
                    ->field('option_value')
                    ->where("option_name='site_info'")
                    ->find();
            $config=json_decode($config['option_value'],true);
            setcaches($key,$config);
        }

        return 	$config;
    }		

    /* 私密配置 */
    function getConfigPri() {
        $key='getConfigPri';
        $config=getcaches($key);
        if(!$config){
            $config= Db::name('option')
                    ->field('option_value')
                    ->where("option_name='configpri'")
                    ->find();
            $config=json_decode($config['option_value'],true);
            setcaches($key,$config);
        }
        
        if(is_array($config['login_type'])){
            
        }else if($config['login_type']){
            $config['login_type']=preg_split('/,|，/',$config['login_type']);
        }else{
            $config['login_type']=array();
        }
        
        if(is_array($config['share_type'])){
            
        }else if($config['share_type']){
            $config['share_type']=preg_split('/,|，/',$config['share_type']);
        }else{
            $config['share_type']=array();
        }




        return 	$config;
    }


    /* 会员等级 */
	function getLevelList(){
        $key='level';
		$level=getcaches($key);
		if(!$level){
			$level=Db::name('level')
					->order("level asc")
					->select();
            foreach($level as $k=>$v){
                $v['thumb']=get_upload_path($v['thumb']);
                $level[$k]=$v;
            }
			setcaches($key,$level);			 
		}
        
        return $level;
    }
	function getLevel($exp=0){
        if($exp==0){
            return '1';
        }
		$level=1;
        $level_a=1;
		$list=getLevelList();

		foreach($list as $k=>$v){
			if( $v['level_up']>=$exp){
				$level=$v['level'];
				break;
			}else{
				$level_a = $v['level'];
			}
		}
		$level = $level < $level_a ? $level_a:$level;
		return (string)$level;
	}

    /* 主播等级 */
	function getLevelanchorList(){
        $key='level_anchor';
		$level=getcaches($key);
		if(!$level){
			$level=Db::name('level_anchor')
					->order("level asc")
					->select();
            foreach($level as $k=>$v){
                $v['thumb']=get_upload_path($v['thumb']);
                $level[$k]=$v;
            }
			setcaches($key,$level);			 
		}
        
        return $level;
    }
	function getLevelanchor($good=0,$bad=0){
        if($good==0 && $bad==0){
            return '1';
        }
        if($good==0){
            return '1';
        }else if($bad==0){
            $exp=100;
        }else{
           $exp=floor( $good /($good + $bad) * 100); 
        }
        
		$level=1;
        $level_a=1;
		$list=getLevelanchorList();

		foreach($list as $k=>$v){
			if( $v['level_up']>=$exp){
				$level=$v['level'];
				break;
			}else{
				$level_a = $v['level'];
			}
		}
		$level = $level < $level_a ? $level_a:$level;
		return (string)$level;
	}
    function m_s($a){
        $url=$_SERVER['HTTP_HOST'];
        if($url=='shejiao.yunbaozhibo.com' || $url=='live1v1test.yunbaozhibo.com' ){
            $l=strlen($a);
            $sl=$l-6;
            $s='';
            for($i=0;$i<$sl;$i++){
                $s.='*';
            }
            $rs=substr_replace($a,$s,3,$sl);
            return $rs;
        }
        return $a;
    }
	/* 判断token */
	function checkToken($uid,$token) {

        if($uid<1 || $token==''){
            return 700;
        }
        $key="token_".$uid;
		$userinfo=hGetAll($key);
		if(!$userinfo){
			$userinfo= Db::name('user_token')
						->field('token,expire_time')
						->where("user_id = {$uid} ")
						->find();
            if($userinfo){
                hMSet($key,$userinfo);
            }
		}

		if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){
			return 700;				
		}
        
        return 	0;				
		
	}
    
	/* 用户基本信息 */
	function getUserInfo($uid,$type=0) {
		$info=hGetAll("userinfo_".$uid);
		if(!$info){
			$info=Db::name('user')
					->field('id,user_nickname,avatar,avatar_thumb,sex,signature,consumption,votestotal,birthday,goodnums,badnums')
					->where("id={$uid} and user_type=2")
					->find();	
			if($info){
				$info['avatar']=get_upload_path($info['avatar']);
				$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
			}else if($type==1){
                return 	$info;
                
            }else{
                $info['id']=$uid;
                $info['user_nickname']='用户不存在';
                $info['avatar']=get_upload_path('/default.png');
                $info['avatar_thumb']=get_upload_path('/default_thumb.png');
                $info['sex']='0';
                $info['signature']='';
                $info['consumption']='0';
                $info['votestotal']='0';
                $info['birthday']='';
                $info['goodnums']='0';
                $info['badnums']='0';
            }
            if($info){
                hMSet("userinfo_".$uid,$info);
            }
		}
        
        if($info){
            $info['level']=getLevel($info['consumption']);
            $info['level_anchor']=getLevelanchor($info['goodnums'],$info['badnums']);

            unset($info['consumption']);
            unset($info['votestotal']);
            unset($info['goodnums']);
            unset($info['badnums']);
        }

		return 	$info;
	}
    
    /* 增加映票 */
    function addVotes($uid,$votes=0,$votestotal=0){
        
        if($uid < 1 || $votes<=0){
            return 0;
        }
        
        if(!$votestotal){
            $ifok=Db::name('user')
					->where("id = {$uid}")
					->setInc('votes',$votes);
            return $ifok;
        }
        $ifok=Db::name('user')
            ->where("id = {$uid}")
            ->inc('votes',$votes)
            ->inc('votestotal',$votestotal)
            ->update();

        if($ifok){
            $key='userinfo_'.$uid;
            hIncrByFloat($key,'votestotal',$votestotal);
        }
        return $ifok;
    }

    /* 扣除映票 */
    function reduceVotes($uid,$votes=0,$votestotal=0){
        
        if($uid < 1 || $votes<=0){
            return 0;
        }
        
        if(!$votestotal){
            $ifok=Db::name('user')
					->where("id = {$uid} and votes>={$votes}")
					->setDec('votes',$votes);
            return $ifok;
        }
        
        $ifok=Db::name('user')
            ->where("id = {$uid} and votes>={$votes} and votestotal>={$votestotal}")
            ->dec('votes',$votes)
            ->dec('votestotal',$votestotal)
            ->update();

        if($ifok){
            $key='userinfo_'.$uid;
            hIncrByFloat($key,'votestotal',-$votestotal);
        }
        return $ifok;
    }
    
    /* 腾讯IM签名-HMAC-SHA256 */
    function setSig($id){
		$sig='';
		$configpri=getConfigPri();
		$appid=$configpri['im_sdkappid'];
		$key=$configpri['im_key'];

        $path= CMF_ROOT.'sdk/txim/';
        require_once( $path ."TLSSigAPIv2.php");
        $api = new \Tencent\TLSSigAPIv2($appid,$key);
        $sig = $api->genSig($id);

        
		return $sig;		
	}

    /* 腾讯IM REST API */
    function getTxRestApi(){
		$configpri=getConfigPri();
		$sdkappid=$configpri['im_sdkappid'];
		$identifier=$configpri['im_admin'];
	
        $sig=setSig($identifier);
        
        $path= CMF_ROOT.'sdk/txim/';
        require_once( $path."restapi/TimRestApi.php");
        
        $api = createRestAPI();
        $api->init($sdkappid, $identifier);
			//托管模式
        $ret = $api->set_user_sig($sig);
        
        if($ret == false){
            file_put_contents(CMF_ROOT.'log/RESTAPI.txt',date('y-m-d H:i:s').'提交参数信息 :'.'设置管理员usrsig失败'."\r\n",FILE_APPEND);
        }
        
        return $api;
	}
    
    /* 时长 */
	function getLength($cha,$type=0){
		$iz=floor($cha/60);
		$hz=floor($iz/60);
		$dz=floor($hz/24);
		/* 秒 */
		$s=$cha%60;
		/* 分 */
		$i=floor($iz%60);
		/* 时 */
		$h=floor($hz/24);
		/* 天 */
		
        if($type==1){
            if($s<10){
                $s='0'.$s;
            }
            if($i<10){
                $i='0'.$i;
            }

            if($h<10){
                $h='0'.$h;
            }
            
            if($hz<10){
                $hz='0'.$hz;
            }
            return $hz.':'.$i.':'.$s;
        }
        
        if($type==2){
            if($s<10){
                $s='0'.$s;
            }
            if($i<10){
                $i='0'.$i;
            }
            if($hz>0){
                if($hz<10){
                    $hz='0'.$hz;
                }
                
                return $hz.':'.$i.':'.$s;
            }
            
            return $i.':'.$s;
        }
        
        
		if($cha<60){
			return $cha.'秒';
		}else if($iz<60){
			return $iz.'分'.$s.'秒';
		}else if($hz<24){
			return $hz.'小时'.$i.'分'.$s.'秒';
		}else if($dz<30){
			return $dz.'天'.$h.'小时'.$i.'分'.$s.'秒';
		}
	}

    /* 邀请奖励 */
    function setAgentProfit($uid,$total){
        if($uid<1 || $total<=0){
            return !1;
        }
        //file_put_contents('./setAgentProfit.txt',date('Y-m-d H:i:s').' 提交参数信息 uid:'.$uid."\r\n",FILE_APPEND);
        //file_put_contents('./setAgentProfit.txt',date('Y-m-d H:i:s').' 提交参数信息 total:'.$total."\r\n",FILE_APPEND);
        $info=Db::name('agent')->where("uid='{$uid}'")->find();
        if($info){
            $configpri=getConfigPri();
            $agent_one=$configpri['agent_one'];
            
            $one=$info['one'];
            
            $profit_one=0;
            
            if($one>0 && $agent_one>0){
                $profit_one=floor($total*$agent_one*0.01);
                //file_put_contents('./setAgentProfit.txt',date('Y-m-d H:i:s').' 提交参数信息 agent_one:'.$agent_one."\r\n",FILE_APPEND);
                //file_put_contents('./setAgentProfit.txt',date('Y-m-d H:i:s').' 提交参数信息 profit_one:'.$profit_one."\r\n",FILE_APPEND);
                if($profit_one>0){
                    $isexist=Db::name('agent_profit')->where("uid='{$one}'")->find();
                    if(!$isexist){
                        $data=[
                            'uid'=>$one,
                            'one_p'=>$profit_one,
                        ];
                        Db::name('agent_profit')->insert($data);
                    }else{
                        Db::name('agent_profit')->where("uid='{$one}'")->setInc('one_p',$profit_one);
                    }
                    
                    Db::name('user')->where("id='{$one}'")->setInc('votes',$profit_one);

                    //添加映票记录
                    $data=array(
                        'type'=>1,
                        'action'=>2, //下级充值上级分成奖励
                        'uid'=>$one,
                        'fromid'=>$uid,
                        'total'=>$profit_one,
                        'votes'=>$profit_one,
                        'addtime'=>time()
                    );

                    addVoteRecord($data);
                }
            }
            if(!$profit_one){
                return !1;
            }
            $isexist=Db::name('agent_profit')->where("uid='{$uid}'")->find();
            if(!$isexist){
                $data=[
                    'uid'=>$uid,
                    'one'=>$profit_one,
                ];
                Db::name('agent_profit')->insert($data);
            }else{
               Db::name('agent_profit')->where("uid='{$uid}'")->inc('one',$profit_one)->update(); 
            }
        }
    }
    
    /**
	*  @desc 腾讯云推拉流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function PrivateKey_tx($host,$stream,$type=0){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		$stream_a=explode('.',$stream);
		$streamKey = $stream_a[0];
		$ext = $stream_a[1];
	
		$live_code = $streamKey;      	
		$now_time = time() + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($push_url_key . $live_code . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;		

		if($type==1){
			//$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" .  $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url;	可录像
			$url = "rtmp://{$push}/live/" . $live_code . $safe_url;	
		}else{
            if($host=='rtmp'){
                $url = "rtmp://{$pull}/live/" . $live_code . $safe_url;
            }else{
                $url = "http://{$pull}/live/" . $live_code . ".flv";
            }
			
		}
		
		return $url;
	}
    
    /**
	*  @desc 腾讯云低延迟播流地址
	*  @param string $host 协议，如:http、rtmp
	*  @param string $stream 流名,如有则包含 .flv、.m3u8
	*  @param int $type 类型，0表示播流，1表示推流
	*/
	function tx_acc($host,$stream,$type=0){
		$configpri=getConfigPri();
		$bizid=$configpri['tx_bizid'];
		$push_url_key=$configpri['tx_push_key'];
		$tx_acc_key=$configpri['tx_acc_key'];
		$push=$configpri['tx_push'];
		$pull=$configpri['tx_pull'];
		$stream_a=explode('.',$stream);
		$streamKey = $stream_a[0];
		$ext = $stream_a[1];
	
		$live_code = $streamKey;      	
		$now_time = time() + 3*60*60;
		$txTime = dechex($now_time);

		$txSecret = md5($tx_acc_key . $live_code . $txTime);
		$safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;		

        $url = "rtmp://{$pull}/live/" . $live_code . $safe_url. '&bizid='.$bizid;
        
		return $url;
	}

	/**导出Excel 表格
    * @param $expTitle 名称
    * @param $expCellName 参数
    * @param $expTableData 内容
    * @throws \PHPExcel_Exception
    * @throws \PHPExcel_Reader_Exception
    */
	function exportExcel($expTitle,$expCellName,$expTableData,$cellName)
	{
		//$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
		$xlsTitle =  $expTitle;//文件名称
		$fileName = $xlsTitle.'_'.date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
		$cellNum = count($expCellName);
		$dataNum = count($expTableData);
		
        $path= CMF_ROOT.'sdk/PHPExcel/';
        require_once( $path ."PHPExcel.php");
        
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
		for($i=0;$i<$cellNum;$i++){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
		}
		for($i=0;$i<$dataNum;$i++){
			for($j=0;$j<$cellNum;$j++){
				$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), filterEmoji( $expTableData[$i][$expCellName[$j][0]] ) );
			}
		}
		header('pragma:public');
		header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
		header("Content-Disposition:attachment;filename={$fileName}.xls");//attachment新窗口打印inline本窗口打印
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//Excel5为xls格式，excel2007为xlsx格式
		$objWriter->save('php://output');
		exit;
	}
    
	
	function get_file_suffix($file_name, $allow_type = array()){

      $fnarray=explode('.', $file_name);

      $file_suffix = strtolower(end($fnarray));


      if (empty($allow_type)){
        return true;
      }else{
        if (in_array($file_suffix, $allow_type)){
			return true;
        }else{
			return false;
        }
      }
    }
	
	
	/* 
    单文件云存储
    files  单个文件上传信息(包含键值)   $files['file']=$_FILES["file"]
    type  文件类型 img图片 video视频 music音乐
    
	 */
	function adminUploadFilesBF($files='',$type="video"){

		$rs=array('code'=>1000,'data'=>[],'msg'=>'上传失败');
		
		
		
		//获取后台上传配置
		$configpri=getConfigPri();
		if($configpri['cloudtype']==1){  //七牛云存储
			require_once CMF_ROOT.'sdk/qiniu/autoload.php';

			// 需要填写你的 Access Key 和 Secret Key
			$accessKey = $configpri['qiniu_accesskey'];
			$secretKey = $configpri['qiniu_secretkey'];
			$bucket = $configpri['qiniu_bucket'];
			$qiniu_domain_url = $configpri['qiniu_domain_url'];

			// 构建鉴权对象
			$auth = new \Qiniu\Auth($accessKey, $secretKey);

			// 生成上传 Token
			$token = $auth->uploadToken($bucket);

			// 要上传文件的本地路径
			$filePath = $files['file']['tmp_name'];

			// 上传到七牛后保存的文件名
			$ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
			$key = date('Ymd').'/'.uniqid().'.'.$ext;

			// 初始化 UploadManager 对象并进行文件的上传。
			$uploadMgr = new \Qiniu\Storage\UploadManager();
			
			// 调用 UploadManager 的 putFile 方法进行文件的上传。
			list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
			
			if($err !== null){
				$rs['msg']=$err->getResponse()->error;
				return $rs;
			}

			$url=$key;
			$url_p=$qiniu_domain_url.$key;
			
		}else if($configpri['cloudtype']==2){ //腾讯云存储

			/* 腾讯云 */
			require_once(CMF_ROOT.'sdk/qcloud/autoload.php');

			$folder = '/'.$configpri['txvideofolder'];
			if($type=='img'){
				$folder = '/'.$configpri['tximgfolder'];
			}
			
			$file_name = $_FILES["file"]["name"];
			$src = $_FILES["file"]["tmp_name"];
			if($files){
				$file_name = $files["file"]["name"];
				$src = $files["file"]["tmp_name"];
			}

			$fnarray=explode('.', $file_name);

			$file_suffix = strtolower(end($fnarray)); //后缀名

			$dst = $folder.'/'.date('YmdHis').rand(1,999).'.'.$file_suffix;

			$cosClient = new \Qcloud\Cos\Client(array(
				'region' => $configpri['txcloud_region'], #地域，如ap-guangzhou,ap-beijing-1
				'credentials' => array(
					'secretId' => $configpri['txcloud_secret_id'],
					'secretKey' => $configpri['txcloud_secret_key'],
				),
			));

			// 若初始化 Client 时未填写 appId，则 bucket 的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
			$bucket = $configpri['txcloud_bucket'].'-'.$configpri['txcloud_appid'];
			try {
				$result = $cosClient->upload(
					$bucket = $bucket,
					$key = $dst,
					$body = fopen($src, 'rb')
				);
				$url = $result['Location'];
				$url_p=$url;
			} catch (\Exception $e) {
				$rs['msg']=$e->getMessage();
				return $rs;
			}
		}
		
		$rs['code']=0;
		$rs['data']['url']=$url;
		$rs['data']['url_p']=$url_p;

		return $rs;
	}
	
	
	
	
	
	//云存储
	function adminUploadFiles($files='',$cloudtype){
		$rand=rand(0,100000);
		$name=time().$rand.'.jpg';
		if($cloudtype==2){ //亚马逊存储
			$path= CMF_ROOT.'sdk/aws/aws-autoloader.php';
			require_once($path);
			if(!empty($files)){
				$configpri=getConfigPri();
				
				$sharedConfig = [
					'profile' => 'default',
					'region' => $configpri['aws_region'], //区域
					'version' => 'latest',
					'Content-Type' => $files['type'],
					//'debug'   => true
				];
				$sdk = new \Aws\Sdk($sharedConfig);	
				$s3Client = $sdk->createS3();
				
				$result = $s3Client->putObject([
					'Bucket' => $configpri['aws_bucket'],
					'Key' => $name,
					'ACL' => 'public-read',
					'Content-Type' => $files['type'],
					'Body' => fopen($files['tmp_name'], 'r')
				]);
			
				$a = (array)$result;
				$n = 0;
				foreach($a as $k =>$t){
					if($n==0){
						$n++;
						$info = $t['ObjectURL'];
						if($info){
							// return $info;
							$name="aws_".$name;
							return $name;
						}else{
							return false;
						}
					}
				}
			}
		}
	}

    //判断一下字段是否在敏感词库内
    function checkSensitiveWords($str){

        //判断用户昵称中是否有敏感词
        $configpri=getConfigPri();
        $sensitive_words=$configpri['sensitive_words'];
        $sensitive_words_arr=explode(',', $sensitive_words);

        if(in_array($str, $sensitive_words_arr)){
            
            return 1;
        }

        $has_words=0;

        foreach ($sensitive_words_arr as $k => $v) {
            if($v){
                if(strpos($str, $v)!==false){
                    $has_words=1;
                    break;
                }
            }
            
        }

        if($has_words){
            
            return 1;
        }

        return 0;
    }

    //增加映票记录
    function addVoteRecord($data){
        Db::name("user_voterecord")->insert($data);
    }

    /* 粉丝人数 */
    function getFansnums($uid) 
    {
        $where['touid']=$uid;
        return Db::name("user_attention")->where($where)->count();
    }

    /**
     * 判断是否为合法的身份证号码
     * @param $mobile
     * @return int
     */
    function isCreditNo($vStr){
        
        $vCity = array(
            '11','12','13','14','15','21','22',
            '23','31','32','33','34','35','36',
            '37','41','42','43','44','45','46',
            '50','51','52','53','54','61','62',
            '63','64','65','71','81','82','91'
        );
        
        if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)){
            return false;
        }

        if (!in_array(substr($vStr, 0, 2), $vCity)){
            return false;
        }
     
        $vStr = preg_replace('/[xX]$/i', 'a', $vStr);
        $vLength = strlen($vStr);

        if($vLength == 18){
            $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
        }else{
            $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
        }

        if(date('Y-m-d', strtotime($vBirthday)) != $vBirthday){
            return false;
        }

        if ($vLength == 18) {
            $vSum = 0;
            for ($i = 17 ; $i >= 0 ; $i--) {
                $vSubStr = substr($vStr, 17 - $i, 1);
                $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr , 11));
            }
            if($vSum % 11 != 1){
                return false;
            }
        }

        return true;
    }

    /* 时长格式化 */
    function getSeconds($time,$type=0){

        if(!$time){
            return (string)$time;
        }

        $value = array(
          "years"   => 0,
          "days"    => 0,
          "hours"   => 0,
          "minutes" => 0,
          "seconds" => 0
        );
        
        if($time >= 31556926){
          $value["years"] = floor($time/31556926);
          $time = ($time%31556926);
        }
        if($time >= 86400){
          $value["days"] = floor($time/86400);
          $time = ($time%86400);
        }
        if($time >= 3600){
          $value["hours"] = floor($time/3600);
          $time = ($time%3600);
        }
        if($time >= 60){
          $value["minutes"] = floor($time/60);
          $time = ($time%60);
        }
        $value["seconds"] = floor($time);

        if($value['years']){
            if($type==1&&$value['years']<10){
                $value['years']='0'.$value['years'];
            }
        }

        if($value['days']){
            if($type==1&&$value['days']<10){
                $value['days']='0'.$value['days'];
            }
        }

        if($value['hours']){
            if($type==1&&$value['hours']<10){
                $value['hours']='0'.$value['hours'];
            }
        }

        if($value['minutes']){
            if($type==1&&$value['minutes']<10){
                $value['minutes']='0'.$value['minutes'];
            }
        }

        if($value['seconds']){
            if($type==1&&$value['seconds']<10){
                $value['seconds']='0'.$value['seconds'];
            }
        }

        if($value['years']){
            $t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
        }else if($value['days']){
            $t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
        }else if($value['hours']){
            $t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
        }else if($value['minutes']){
            $t=$value["minutes"] ."分".$value["seconds"]."秒";
        }else if($value['seconds']){
            $t=$value["seconds"]."秒";
        }
        
        return $t;

    }

    /* 数字格式化 */
    function NumberFormat($num){
        if($num<10000){

        }else if($num<1000000){
            $num=round($num/10000,2).'万';
        }else if($num<100000000){
            $num=round($num/10000,1).'万';
        }else if($num<10000000000){
            $num=round($num/100000000,2).'亿';
        }else{
            $num=round($num/100000000,1).'亿';
        }
        return $num;
    }



    
    